/**
 * 
 */
package broadcastreceiver;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.google.gson.Gson;

import components.SMSRecievingCommandFactory;
import components.SMSCommandManager;
import components.SMSLogManager;

import controller.TabNavigation;
import data.RecievingSMSCommand;
import data.SMSLog;
import android.app.ActionBar.Tab;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

/**
 * @author User
 * 
 */
public class SMSBroadcastReceiver extends BroadcastReceiver {

	private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
	private static final String TAG = "SMSBroadcastReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		// Toast.makeText(
		// context,
		// "recieved: ",
		// Toast.LENGTH_LONG).show();
		

		if (intent.getAction().equals(SMS_RECEIVED)) {

			//Toast.makeText(context, "receive " + intent.getAction(),
			//		Toast.LENGTH_LONG).show();
			
			SmsMessage[] messages = getSMSMessageArray(context, intent);

			Context remoteControl = null;

			if (TabNavigation.RemoteControllerContext == null) {

				try {
					remoteControl = context.createPackageContext(
							common.Constant.PACKET_NAME,
							Context.MODE_WORLD_READABLE);
				} catch (NameNotFoundException e) {
					return;
				}

			} else {
				remoteControl = TabNavigation.RemoteControllerContext;
			}

			String settingPhoneNumber = SMSCommandManager
					.sharedPhoneNumber(remoteControl);

			if (settingPhoneNumber == null) {
				return;
			}

			// Debug mode
			if (settingPhoneNumber.equals("5554")
					|| settingPhoneNumber.equals("5556")) {
				settingPhoneNumber = "1555521" + settingPhoneNumber;
			}

//			Toast.makeText(context, "Message from shared" + settingPhoneNumber,
//					Toast.LENGTH_LONG).show();

			for (SmsMessage smsMessage : messages) {
				String phone = smsMessage.getOriginatingAddress();
				if (phone != null) {
					phone = phone.replace("+84", "0");
				}
				
				Toast.makeText(context, "message from phone " + phone,
						Toast.LENGTH_LONG).show();
				if (phone != null) {
					if (settingPhoneNumber.equals(phone)) {
						String messageContent = smsMessage.getMessageBody();

						// if my application have not started yet, start new
						// activity
						Intent startActivityIntent = new Intent(common.Constant.ACTION_MAIN);
						startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						//startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
						context.startActivity(startActivityIntent);
						
						// else if My application started, just send broadcast

						Intent newActivityIntent = new Intent(context,
								TabNavigation.class);
						newActivityIntent
								.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(newActivityIntent);

						Intent newIntent = new Intent(
								TabNavigation.ACTION_SMS_RECIEVER);

						// newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						// newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);

						//String json = new Gson().toJson(smsCommand);
						newIntent.putExtra(
								common.Constant.BROADCAST_REIEVER_MESSAGE, messageContent
								);
						newIntent.putExtra(common.Constant.BROADCAST_RECIEVER_PHONE_NUMBER, phone);
						context.sendBroadcast(newIntent);

						abortBroadcast();

						Timer timer = new Timer();
						final Context c = remoteControl;
						final SmsMessage mes = smsMessage;
						deleteMessage(c, mes);
						timer.schedule(new TimerTask() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								deleteMessage(c, mes);
							
							}
						}, 5000);
					
					}
				}
			}

		}
	}

	private void deleteMessage(Context context, SmsMessage msg) {
	    Uri deleteUri = Uri.parse("content://sms");
	    Cursor c = context.getContentResolver().query(deleteUri, null, null,
	            null, null);
	    while (c.moveToNext()) {
	        try {
	            // Delete the SMS
	            String pid = c.getString(0); // Get id;
	            int addressIndex = c.getColumnIndexOrThrow("address");
	            String address = c.getString(addressIndex);
	            int dateIndex = c.getColumnIndex("date_sent");
	            String date = c.getString(dateIndex);
	            
	            if (address.equalsIgnoreCase(msg.getOriginatingAddress())
	            		&& date.equalsIgnoreCase(String.valueOf(msg.getTimestampMillis()))) {
	            	String uri = "content://sms/" + pid;
	           context.getContentResolver().delete(Uri.parse(uri),
	                    null, null);
	            return;
	            }
	        } catch (Exception e) {
	        }
	    }
	  
	}
	
	private SmsMessage[] getSMSMessageArray(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");
			final SmsMessage[] messages = new SmsMessage[pdus.length];
			for (int i = 0; i < pdus.length; i++) {

				messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				// String phone = messages[i].getOriginatingAddress();
				//
				// if (phone != null) {
				// if (settingPhoneNumber.equals(phone)) {
				// Toast.makeText(
				// context,
				// "Message recieved: " + messages[0].getMessageBody()
				// + " from " + messages[0].getOriginatingAddress(),
				// Toast.LENGTH_LONG).show();
				// abortBroadcast();
				// }
				// }
			}

			return messages;

		}

		return new SmsMessage[0];
	}
}